package com.football;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

public class RecordActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_record);

		final VideoView mVideoView = (VideoView) findViewById(R.id.video_view);
		mVideoView
				.setVideoPath("http://techslides.com/demos/sample-videos/small.mp4");
		MediaController mediaController = new MediaController(this);
		mediaController.setAnchorView(mVideoView);
		mVideoView.setMediaController(mediaController);
		mVideoView.requestFocus();
		mVideoView.setOnPreparedListener(new OnPreparedListener() {
			// Close the progress bar and play the video
			public void onPrepared(MediaPlayer mp) {
				mVideoView.start();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.record, menu);
		return true;
	}

	private static final int VIDEO_CAPTURE = 101;
	Uri videoUri;

	public void startRecordingVideo() {
		if (getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA_FRONT)) {
			Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
			File mediaFile = new File(Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/myvideo.mp4");
			videoUri = Uri.fromFile(mediaFile);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
			startActivityForResult(intent, VIDEO_CAPTURE);
		} else {
			Toast.makeText(this, "No camera on device", Toast.LENGTH_LONG)
					.show();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VIDEO_CAPTURE) {
			if (resultCode == RESULT_OK) {
				Toast.makeText(this,
						"Video has been saved to:\n" + data.getData(),
						Toast.LENGTH_LONG).show();
				playbackRecordedVideo();
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "Video recording cancelled.",
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this, "Failed to record video",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	public void playbackRecordedVideo() {
		VideoView mVideoView = (VideoView) findViewById(R.id.video_view);
		mVideoView.setVideoURI(videoUri);
		mVideoView.setMediaController(new MediaController(this));
		mVideoView.requestFocus();
		mVideoView.start();
	}

}
